package com.autotest.nore.controller;

import com.autotest.nore.service.MockService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/autotest/mock")
public class MockController {

    @Autowired
    private MockService mockService;

    /**
     * 处理所有Mock请求（支持所有HTTP方法）
     */
    @RequestMapping(value = "/**",
            method = {RequestMethod.GET, RequestMethod.POST,
                    RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.PATCH})
    public ResponseEntity<?> handleMockRequest(
            HttpServletRequest request,
            UriComponentsBuilder uriBuilder) {

        try {
            // 1. 提取完整请求路径（包含模块前缀）
            String fullPath = extractPathFromRequest(request);

            // 2. 解析模块前缀和API路径
            String[] parts = parseModuleAndPath(fullPath);
            String modulePrefix = parts[0];
            String apiPath = parts[1];

            // 3. 获取请求方法
            RequestMethod method = RequestMethod.valueOf(request.getMethod());

            // 4. 调用Mock服务，传入模块前缀和API路径
            return mockService.mockResponse(modulePrefix, apiPath, method, request);

        } catch (IllegalArgumentException e) {
            log.error("Invalid HTTP method: {}", request.getMethod(), e);
            return ResponseEntity.badRequest().body(Map.of(
                    "error", "Unsupported HTTP method",
                    "method", request.getMethod()
            ));
        } catch (Exception e) {
            log.error("Mock request processing failed", e);
            return ResponseEntity.internalServerError().body(Map.of(
                    "error", "Internal server error",
                    "message", e.getMessage()
            ));
        }
    }

    /**
     * 从请求中提取API路径（去掉/mock前缀）
     */
    private String extractPathFromRequest(HttpServletRequest request) {
        String fullPath = request.getRequestURI();

        // 去掉context path（如果有）
        String contextPath = request.getContextPath();
        if (contextPath != null && !contextPath.isEmpty()) {
            fullPath = fullPath.substring(contextPath.length());
        }

        // 去掉/mock前缀
        if (fullPath.startsWith("/autotest/mock")) {
            fullPath= fullPath.substring(14); // 去掉"/mock"共5个字符+1个斜杠
        }

        return fullPath;
    }

    /**
     * 解析模块前缀和API路径
     * 输入示例: "/user_service/api/users" → ["user_service", "/api/users"]
     */
    private String[] parseModuleAndPath(String fullPath) {
        // 去掉开头的斜杠
        String path = fullPath.startsWith("/") ? fullPath.substring(1) : fullPath;

        // 分割第一部分作为模块前缀
        int firstSlash = path.indexOf('/');
        if (firstSlash > 0) {
            String modulePrefix = path.substring(0, firstSlash);
            String apiPath = path.substring(firstSlash);
            return new String[]{modulePrefix, apiPath};
        }

        // 没有模块前缀的情况
        return new String[]{"", path};
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, String>> healthCheck() {
        return ResponseEntity.ok(Map.of(
                "status", "UP",
                "service", "Mock Service"
        ));
    }

    /**
     * 处理未匹配的路径
     */
    @RequestMapping(value = "/**", method = RequestMethod.OPTIONS)
    public ResponseEntity<?> handleOptions() {
        return ResponseEntity.ok().build();
    }
}